/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml.viewer;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import ebml.ElementType;
import ebml.VInteger;
import ebml.viewer.table.ExtendedColumn;
import ebml.viewer.table.ExtendedTableModel;
import ebml.viewer.table.FormatTableCellRenderer;

/** Contains EBML element statistics. */
public final class ElementStatsTableModel extends ExtendedTableModel {

    private static final ResourceBundle RESOURCES = ResourceBundle.getBundle(Resources.class.getName());

    private static final ExtendedColumn[] COLUMNS = {
            new ExtendedColumn("table.elementStats.identifier", VInteger.class, 75, new ElementIdentifierTableCellRenderer(), new ElementIdentifierComparator()),
            new ExtendedColumn("table.elementStats.name", String.class, 100, null, null),
            new ExtendedColumn("table.elementStats.type", ElementType.class, 100, new ElementTypeTableCellRenderer(), null),
            new ExtendedColumn("table.elementStats.instanceCount", Integer.class, 75, new FormatTableCellRenderer(NumberFormat.getIntegerInstance(), SwingConstants.RIGHT), null),
            new ExtendedColumn("table.elementStats.totalSize", Long.class, 100, new FormatTableCellRenderer(NumberFormat.getIntegerInstance(), SwingConstants.RIGHT), null),
            new ExtendedColumn("table.elementStats.averageSize", Double.class, 100, new FormatTableCellRenderer(NumberFormat.getInstance(), SwingConstants.RIGHT), null),
    };


    private final List<Row> data;


    /** Creates a new <code>ElementStatsTableModel</code> object. */
    public ElementStatsTableModel() {
        super(COLUMNS);
        data = new ArrayList<Row>();
    }


    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        return RESOURCES.getString(getColumnIdentifier(columnIndex));
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Row row = data.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return row.identifier;
            case 1:
                return row.name;
            case 2:
                return row.type;
            case 3:
                return row.instanceCount;
            case 4:
                return row.totalSize;
            case 5:
                return row.averageSize;
            default:
                throw new AssertionError(columnIndex);
        }
    }


    /**
     * Updates the element statistics.
     *
     * @param identifier the element identifier
     * @param name the element name
     * @param type the element type
     * @param size the element size
     *
     * @throws NullPointerException if <code>identifier</code> is <code>null</code>
     */
    public void processElement(final VInteger identifier, final String name, final ElementType type, final VInteger size) {
        if (identifier == null) {
            throw new NullPointerException("identifier is null");
        }
        if (SwingUtilities.isEventDispatchThread()) {
            processElementUnsafe(identifier, name, type, size);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    processElementUnsafe(identifier, name, type, size);
                }
            });
        }
    }

    private void processElementUnsafe(VInteger identifier, String name, ElementType type, VInteger size) {
        int rowIndex = data.size() - 1;
        while (rowIndex >= 0 && !data.get(rowIndex).identifier.equals(identifier)) {
            rowIndex--;
        }
        if (rowIndex >= 0) {
            Row row = data.get(rowIndex);
            row.instanceCount++;
            row.totalSize += size.getValue();
            row.averageSize = (double) row.totalSize / row.instanceCount;
            fireTableRowsUpdated(rowIndex, rowIndex);
        } else {
            rowIndex = data.size();
            Row row = new Row(identifier, name, type);
            row.instanceCount++;
            row.totalSize += size.getValue();
            row.averageSize = (double) row.totalSize / row.instanceCount;
            data.add(row);
            fireTableRowsInserted(rowIndex, rowIndex);
        }
    }


    private static final class Row {

        private final VInteger identifier;

        private final String name;

        private final ElementType type;

        private int instanceCount;

        private long totalSize;

        private double averageSize;

        private Row(VInteger identifier, String name, ElementType type) {
            this.identifier = identifier;
            this.name = name;
            this.type = type;
        }

    }

}
